package servlet.dept;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import dao.DepartmentDao;
import entity.Department;

public class QueryAllDeptServlet extends HttpServlet {
	

	/**
	 * 
	 */
	private static final long serialVersionUID = -2755761041154573596L;

	public QueryAllDeptServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String deptName = request.getParameter("deptName");
		deptName = URLDecoder.decode(URLDecoder.decode(StringUtils.isEmpty(deptName) ? "" : deptName, "UTF-8"), "UTF-8");
		DepartmentDao departmentDao = null;
		List<Department> departments = null;
		StringBuffer deptJson = null;
		try {
			departmentDao = new DepartmentDao();
			departments = departmentDao.queryDept(deptName);
			
			// obj to json
			deptJson = new StringBuffer();
			if(departments != null && departments.size() > 0) {
				deptJson.append("{\"retCode\":\"1\",");
				deptJson.append("\"departments\":[");
				for(Department department : departments) {
					deptJson.append("{");
					deptJson.append("\"deptName\":\"").append(department.getDeptName()).append("\",");
					deptJson.append("\"createDate\":\"").append(department.getCreateDate().toString()).append("\"");
					deptJson.append("},");
				}
				deptJson.deleteCharAt(deptJson.length() - 1).append("]}");
			} else {
				deptJson.append("{\"retCode\":\"0\",");
				deptJson.append("\"desc\":\"无记录\"}");
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			out.print(deptJson.toString());
			out.close();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	public void init() throws ServletException {
	}

}
